// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <pollux/substrait/type_utils.h>
#include <pollux/type/type.h>

namespace kumo::pollux::substrait {
    std::vector<std::string_view> getTypesFromCompoundName(
        std::string_view compoundName) {
        // CompoundName is like ARRAY<BIGINT> or MAP<BIGINT,DOUBLE>
        // or ROW<BIGINT,ROW<DOUBLE,BIGINT>,ROW<DOUBLE,BIGINT>>
        // the position of then delimiter is where the number of leftAngleBracket
        // equals rightAngleBracket need to split.
        std::vector<std::string_view> types;
        std::vector<int> angleBracketNumEqualPos;
        auto leftAngleBracketPos = compoundName.find("<");
        auto rightAngleBracketPos = compoundName.rfind(">");
        auto typesName = compoundName.substr(
            leftAngleBracketPos + 1, rightAngleBracketPos - leftAngleBracketPos - 1);
        int leftAngleBracketNum = 0;
        int rightAngleBracketNum = 0;
        for (auto index = 0; index < typesName.length(); index++) {
            if (typesName[index] == '<') {
                leftAngleBracketNum++;
            }
            if (typesName[index] == '>') {
                rightAngleBracketNum++;
            }
            if (typesName[index] == ',' &&
                rightAngleBracketNum == leftAngleBracketNum) {
                angleBracketNumEqualPos.push_back(index);
            }
        }
        int startPos = 0;
        for (auto delimeterPos: angleBracketNumEqualPos) {
            types.emplace_back(typesName.substr(startPos, delimeterPos - startPos));
            startPos = delimeterPos + 1;
        }
        types.emplace_back(std::string_view(
            typesName.data() + startPos, typesName.length() - startPos));
        return types;
    }

    // TODO Refactor using Bison.
    std::string_view getNameBeforeDelimiter(
        const std::string &compoundName,
        const std::string &delimiter) {
        std::size_t pos = compoundName.find(delimiter);
        if (pos == std::string::npos) {
            return compoundName;
        }
        return std::string_view(compoundName.data(), pos);
    }
} // namespace kumo::pollux::substrait
